﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Linq.Expressions;
using System.Security.Claims;
using System.Threading.Tasks;
using Code;
using DB;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Hosting.Internal;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Options;
using Models;

namespace LayuiAdmin.Controllers {
    [Route("api/[action]")]
    [Authorize]
    public class ApiController : Controller {
        #region Account
        [AllowAnonymous]
        public async Task<IActionResult> Login(string username, string password) {
            Result result = new Result();

            using (var context = new SqlServerDB()) {
                password = password.MD5Encrypt64();
                var user = await context.Users.FirstOrDefaultAsync(m =>
                        (m.UserCode.Equals(username) || m.Phone.Equals(username))
                        && m.Password.Equals(password) && m.IsEnable);

                if (user != null) {
                    //var address = await context.Entry(user).Collection(u => u.ShippingAddress).Query().ToListAsync();
                    string AuthenticationType = CookieAuthenticationDefaults.AuthenticationScheme;

                    var identity = new ClaimsIdentity(AuthenticationType);

                    identity.AddClaim(new Claim(ClaimTypes.Sid, user.Id.ToString()));
                    identity.AddClaim(new Claim(ClaimTypes.Name, user.UserName));
                    identity.AddClaim(new Claim("UserType", ((int)user.UserType).ToString()));

                    await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(identity));

                    result.code = 0;
                    result.success = true;
                    result.message = "登陆成功";
                } else {
                    result.code = 1001;
                    result.success = true;
                    result.message = "登陆失败，用户名或密码不正确，或者用户已被冻结";
                }
            }

            return Ok(result);
        }

        public async Task<IActionResult> LogOut(string returnurl) {
            await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
            return Redirect(returnurl ?? "~/");
        }

        public async Task<IActionResult> UserList(int userType, int page, int limit, string userCode, string phone, int level, string userName, int userId = 0) {
            using (var context = new SqlServerDB()) {
                page--;

                IQueryable<Users> queryable;

                if (userType == (int)UserTypes.管理员 || userType == (int)UserTypes.超级管理员) {
                    queryable = context.Users.Where(m => m.UserType == UserTypes.管理员 || m.UserType == UserTypes.超级管理员);
                } else {
                    queryable = context.Users.Where(m => m.UserType == UserTypes.普通用户);
                }

                if ((userCode + "").Length > 0) {
                    queryable = queryable.Where(m => m.UserCode.Contains(userCode));
                }

                if ((userName + "").Length > 0) {
                    queryable = queryable.Where(m => m.UserName.Contains(userName));
                }

                if ((phone + "").Length > 0) {
                    queryable = queryable.Where(m => m.Phone.Contains(phone));
                }

                if (level > 0) {
                    queryable = queryable.Where(m => (int)m.Level == level);
                }

                if (userId > 0) {
                    queryable = queryable.Where(m => m.ParentId == userId);
                }

                List<Users> uList = await queryable.ToListAsync();


                int count = uList.Count();

                return Ok(new {
                    code = 0,
                    msg = "",
                    count,
                    data = uList.Skip(page * limit).Take(limit).ToJsonString()
                });
            }
        }

        public async Task<IActionResult> FreezeUsers(string ids, bool status) {
            Result result = new Result();
            long UserId = Convert.ToInt64(HttpContext.User.Identity.GetValue(ClaimTypes.Sid));

            using (var context = new SqlServerDB()) {
                if (ids.Length > 0) {
                    List<long> idList = new List<long>();
                    string[] idArray = ids.Split(',');
                    long id = 0;

                    foreach (var i in idArray) {
                        if (long.TryParse(i, out id)) {
                            if (id > 1) {
                                idList.Add(id);
                            }
                        }
                    }

                    if (idList.Count > 0) {
                        if (idList.Count(m => m == UserId) > 0) {
                            result.code = 1002;
                            result.success = true;
                            result.message = $"{(status ? "解冻" : "冻结")}失败，选择了当前登陆用户";
                            return Ok(result);
                        }

                        var list = context.Users.Where(m => idList.Contains(m.Id));

                        if (list.Count() > 0) {
                            foreach (var model in list) {
                                model.IsEnable = status;
                            }

                            context.Users.UpdateRange(list);

                            int flag = await context.SaveChangesAsync();

                            if (flag > 0) {
                                result.code = 0;
                                result.success = true;
                                result.message = status ? "解冻成功" : "冻结成功";
                            } else {
                                result.code = 1002;
                                result.success = true;
                                result.message = $"{(status ? "解冻" : "冻结")}失败，请稍候重试";
                            }

                            return Ok(result);
                        }
                    }
                }
            }


            result.code = 1001;
            result.success = true;
            result.message = $"未选择要{(status ? "解冻" : "冻结")}的数据或选择了超级管理员";

            return Ok(result);
        }

        public async Task<IActionResult> DelUsers(string ids) {
            Result result = new Result();
            long UserId = Convert.ToInt64(HttpContext.User.Identity.GetValue(ClaimTypes.Sid));

            using (var context = new SqlServerDB()) {
                if (ids.Length > 0) {
                    List<long> idList = new List<long>();
                    string[] idArray = ids.Split(',');
                    long id = 0;

                    foreach (var i in idArray) {
                        if (long.TryParse(i, out id)) {
                            if (id > 1) {
                                idList.Add(id);
                            }
                        }
                    }

                    if (idList.Count > 0) {
                        if (idList.Count(m => m == UserId) > 0) {
                            result.code = 1002;
                            result.success = true;
                            result.message = "删除失败，选择了当前登陆用户";
                            return Ok(result);
                        }

                        var list = context.Users.Where(m => idList.Contains(m.Id));

                        if (list.Count() > 0) {
                            foreach (var model in list) {
                                context.Entry(model).Collection(m => m.ShippingAddress).Query().ToList();
                                context.ShippingAddress.RemoveRange(model.ShippingAddress);
                                context.Entry(model).Collection(m => m.Cash).Query().ToList();
                                context.Cashes.RemoveRange(model.Cash);

                                //TODO:要测试
                                var role = await context.UserToRole.FirstOrDefaultAsync(m => m.UserId == model.Id);

                                if (role != null) {
                                    context.UserToRole.Remove(role);
                                }
                            }

                            context.Users.RemoveRange(list);

                            int flag = await context.SaveChangesAsync();

                            if (flag > 0) {
                                result.code = 0;
                                result.success = true;
                                result.message = "删除成功";
                            } else {
                                result.code = 1002;
                                result.success = true;
                                result.message = "删除失败，请稍候重试";
                            }

                            return Ok(result);
                        }
                    }
                }
            }


            result.code = 1001;
            result.success = true;
            result.message = "未选择要删除的数据或选择了超级管理员";

            return Ok(result);
        }

        public async Task<IActionResult> SaveUser([FromBody]Users model) {
            Result result = new Result();
            long role = model.ParentId;
            bool IsAdd = false;

            using (var context = new SqlServerDB()) {
                if (model.UserType == UserTypes.普通用户) {
                    if (context.Users.Count(m => m.Phone == model.Phone && m.Id != model.Id) > 0) {
                        result.code = 2001;
                        result.message = "手机号已被他人使用";
                        return Ok(result);
                    }

                    if ((model.UserCode + "").Length == 0) {
                        model.UserCode = await GetUserCodeAsync(context);
                    }
                } else {
                    model.UserCode = model.UserName;
                }

                if (model.Id > 0) {
                    var IsChange = await context.Users.CountAsync(m => m.Id == model.Id && m.Password == model.Password);

                    if (IsChange == 0) {
                        model.Password = model.Password.MD5Encrypt64();
                    }

                    if (model.UserType == UserTypes.管理员) {
                        if (model.ParentId > 0) {
                            var u2r = await context.UserToRole.FirstOrDefaultAsync(m => m.UserId == model.Id);

                            if (u2r != null) {
                                context.UserToRole.Remove(u2r);
                            }

                            u2r = new UserToRole {
                                UserId = model.Id,
                                RoleId = role
                            };

                            await context.UserToRole.AddAsync(u2r);

                            model.ParentId = 0;
                        }
                    }

                    context.Users.Update(model);
                } else {
                    model.Password = model.Password.MD5Encrypt64();

                    if (model.UserType == UserTypes.管理员) {
                        model.ParentId = 0;
                        IsAdd = true;
                    }

                    await SetTeamCountAsync(model.ParentId, context);

                    await context.Users.AddAsync(model);
                }

                var i = await context.SaveChangesAsync();

                if (i > 0) {
                    if (IsAdd) {
                        await context.UserToRole.AddAsync(new UserToRole {
                            UserId = model.Id,
                            RoleId = role
                        });

                        await context.SaveChangesAsync();
                    }
                    result.code = 0;
                    result.message = "保存成功";
                } else {
                    result.code = 2001;
                    result.message = "保存失败";
                }
            }

            return Ok(result);
        }

        private async Task SetTeamCountAsync(long parentId, SqlServerDB context) {
            var user = await context.Users.FirstOrDefaultAsync(m => m.Id == parentId);

            if (user != null) {
                user.TeamCount = user.TeamCount + 1;
                context.Users.Update(user);

                if (user.ParentId > 0) {
                    await SetTeamCountAsync(user.ParentId, context);
                }
            }
        }

        private async Task<string> GetUserCodeAsync(SqlServerDB context) {
            string userCode = $"{DateTime.Now.ToString("yyMM")}{(BaseCode.GetRandomCode(4))}";
            var user = await context.Users.FirstOrDefaultAsync(m => m.UserCode.Equals(userCode));

            if (user != null) {
                userCode = await GetUserCodeAsync(context);
            }

            return userCode;
        }

        public async Task<IActionResult> SaveRecommend([FromBody]Users model) {
            Result result = new Result();
            using (var context = new SqlServerDB()) {
                if (context.Users.Count(m => m.Phone == model.Phone && m.Id != model.Id) > 0) {
                    result.code = 2001;
                    result.message = "手机号已被他人使用";
                    return Ok(result);
                }

                model.UserType = UserTypes.普通用户;

                if (model.Id == 0) {
                    long id = 0;
                    string strId = HttpContext.User.Identity.GetValue(ClaimTypes.Sid);

                    long.TryParse(strId, out id);

                    model.ParentId = id;
                    model.UserCode = await GetUserCodeAsync(context);

                    if (model.Level == 0) {
                        model.Level = LevelCode.未激活;
                    }

                    if ((model.Password + "").Length == 0) {
                        model.Password = "123456".MD5Encrypt64();
                    }

                    await SetTeamCountAsync(model.ParentId, context);
                    await context.Users.AddAsync(model);
                } else {
                    context.Users.Update(model);
                }

                var i = await context.SaveChangesAsync();

                if (i > 0) {
                    result.code = 0;
                    result.message = "保存成功";
                } else {
                    result.code = 2001;
                    result.message = "保存失败";
                }
            }

            return Ok(result);
        }

        public async Task<IActionResult> ChangePwd([FromBody]dynamic param) {
            Result result = new Result();

            Dictionary<string, string> model =
                    Newtonsoft.Json.JsonConvert.DeserializeObject<Dictionary<string, string>>(param.ToString());

            string oldPwd = model.GetValueOrDefault("oldPwd", ""),
                   newPwd = model.GetValueOrDefault("newPwd", ""),
                   strId = HttpContext.User.Identity.GetValue(ClaimTypes.Sid);

            long Id = 0;
            long.TryParse(strId, out Id);

            using (var context = new SqlServerDB()) {
                var user = await context.Users.FirstOrDefaultAsync(m => m.Id == Id);

                if (user == null) {
                    result.code = 2001;
                    result.message = "非法操作";
                } else {
                    oldPwd = oldPwd.MD5Encrypt64();

                    if (oldPwd.Equals(user.Password)) {
                        user.Password = newPwd.MD5Encrypt64();

                        context.Users.Update(user);

                        var i = await context.SaveChangesAsync();

                        if (i > 0) {
                            result.code = 0;
                            result.message = "保存成功";
                        } else {
                            result.code = 2001;
                            result.message = "保存失败";
                        }
                    } else {
                        result.code = 2001;
                        result.message = "旧密码输入错误";
                    }
                }
            }

            return Ok(result);
        }

        public async Task<IActionResult> SecondaryPwd([FromBody]dynamic param) {
            Result result = new Result();

            Dictionary<string, string> model =
                    Newtonsoft.Json.JsonConvert.DeserializeObject<Dictionary<string, string>>(param.ToString());

            string oldPwd = model.GetValueOrDefault("oldPwd", ""),
                   newPwd = model.GetValueOrDefault("newPwd", ""),
                   strId = HttpContext.User.Identity.GetValue(ClaimTypes.Sid);

            long Id = 0;
            long.TryParse(strId, out Id);

            using (var context = new SqlServerDB()) {
                var user = await context.Users.FirstOrDefaultAsync(m => m.Id == Id);

                if (user == null) {
                    result.code = 2001;
                    result.message = "非法操作";
                } else {
                    if ((user.SecondaryPwd + "").Length > 0) {
                        oldPwd = oldPwd.MD5Encrypt64();
                        if (oldPwd.Equals(user.SecondaryPwd)) {
                            user.SecondaryPwd = newPwd.MD5Encrypt64();
                        } else {
                            result.code = 2001;
                            result.message = "旧密码输入错误";
                        }
                    } else {
                        user.SecondaryPwd = newPwd.MD5Encrypt64();
                    }

                    context.Users.Update(user);
                    var i = await context.SaveChangesAsync();

                    if (i > 0) {
                        result.code = 0;
                        result.message = "保存成功";
                    } else {
                        result.code = 2001;
                        result.message = "保存失败";
                    }
                }
            }

            return Ok(result);
        }

        public async Task<IActionResult> SaveCashInfo([FromBody]CashInfo model) {
            Result result = new Result();

            using (var context = new SqlServerDB()) {
                var user = await context.Users.FirstOrDefaultAsync(m => m.Id == model.Id);

                context.Entry(user).Collection(u => u.Cash).Query().FirstOrDefault();

                if (user.Cash != null && user.Cash.Count > 0) {
                    var c = user.Cash.FirstOrDefault();

                    c.Account = model.Account;
                    c.AccountName = model.AccountName;
                    c.Bank = model.Bank;
                    c.CashType = model.CashType;

                    context.Cashes.Update(c);
                } else {
                    user.Cash = new List<CashInfo> {
                        new CashInfo{
                            Account = model.Account,
                            AccountName = model.AccountName,
                            Bank = model.Bank,
                            CashType = model.CashType
                        }
                    };

                    await context.Cashes.AddAsync(user.Cash.FirstOrDefault());
                }

                var i = await context.SaveChangesAsync();

                if (i > 0) {
                    result.code = 0;
                    result.message = "保存成功";
                } else {
                    result.code = 2001;
                    result.message = "保存失败";
                }
            }

            return Ok(result);
        }

        public async Task<IActionResult> SaveAddresss([FromBody]ShippingAddress model) {
            Result result = new Result();

            using (var context = new SqlServerDB()) {
                var user = await context.Users.FirstOrDefaultAsync(m => m.Id == model.Id);
                context.Entry(user).Collection(u => u.ShippingAddress).Query().FirstOrDefault();

                if (user.ShippingAddress != null && user.ShippingAddress.Count > 0) {
                    var address = user.ShippingAddress.FirstOrDefault();
                    address.Address = model.Address;
                    address.AreaId = model.AreaId;
                    address.CityId = model.CityId;
                    address.Phone = model.Phone;
                    address.ProvinceId = model.ProvinceId;
                    address.Receiver = model.Receiver;

                    context.Users.Update(user);
                } else {
                    user.ShippingAddress = new List<ShippingAddress> {
                        new ShippingAddress{
                            Address = model.Address,
                            AreaId = model.AreaId,
                            CityId = model.CityId,
                            Phone = model.Phone,
                            ProvinceId = model.ProvinceId,
                            Receiver = model.Receiver
                        }
                    };

                    await context.ShippingAddress.AddAsync(user.ShippingAddress.FirstOrDefault());
                }

                var i = await context.SaveChangesAsync();

                if (i > 0) {
                    result.code = 0;
                    result.message = "保存成功";
                } else {
                    result.code = 2001;
                    result.message = "保存失败";
                }
            }

            return Ok(result);
        }

        public async Task<IActionResult> IsSetSecondaryPwd() {
            Result result = new Result();
            using (var context = new SqlServerDB()) {
                long.TryParse(HttpContext.User.Identity.GetValue(ClaimTypes.Sid), out long userId);

                var user = await context.Users.FirstOrDefaultAsync(m => m.Id == userId && m.IsEnable);

                if (user != null) {
                    result.code = 0;
                    result.message = "";

                    if ((user.SecondaryPwd + "").Length > 0) {
                        var cash = await context.Entry(user).Collection(m => m.Cash).Query().FirstOrDefaultAsync(m => m.CashType == CashType.银行卡);

                        if (cash != null) {
                            var settings = context.Settings.Where(m => m.SystemType == SystemType.提现);
                            var systemType = settings.FirstOrDefault(m => m.OtherType == ((int)SystemType.提现手续费).ToString());
                            var multiple = settings.FirstOrDefault(m => m.OtherType == ((int)SystemType.提现倍数).ToString());
                            string strValues = systemType.Values;
                            float value = 0;

                            if (strValues.LastIndexOf('%') > -1) {
                                int.TryParse(strValues.Replace("%", ""), out int iValue);

                                value = (iValue / 100f);
                            } else {
                                float.TryParse(strValues, out value);
                            }



                            result.data = new {
                                strValue = strValues,
                                value,
                                user.Overage,
                                multiple = multiple == null ? "1" : multiple.Values
                            };
                        } else {
                            result.data = false;
                        }
                    } else {
                        result.data = false;
                    }
                } else {
                    result.code = 2001;
                    result.message = "非法操作";
                }
            }
            return Ok(result);
        }

        public async Task<IActionResult> SaveCashLog([FromBody]Dictionary<string, object> data) {
            Result res = new Result();
            string secondaryPwd = "",
                   strPrice = "",
                   fee = "";

            secondaryPwd = data.GetValueOrDefault("secondaryPwd", "").ToString();
            fee = data.GetValueOrDefault("fee", "").ToString();
            strPrice = data.GetValueOrDefault("price", "").ToString();

            decimal.TryParse(strPrice, out decimal price);

            using (var context = new SqlServerDB()) {
                long.TryParse(HttpContext.User.Identity.GetValue(ClaimTypes.Sid), out long userId);

                secondaryPwd = secondaryPwd.MD5Encrypt64();

                var user = await context.Users.FirstOrDefaultAsync(m => m.Id == userId && m.SecondaryPwd.Equals(secondaryPwd) && m.IsEnable);

                if (user != null) {
                    decimal.TryParse(fee, out decimal handlingfee);

                    decimal realPrice = Math.Round(price + price * handlingfee, 2, MidpointRounding.AwayFromZero);

                    if (realPrice > user.Overage) {
                        res.code = 2001;
                        res.message = "申请提现金额大于可提现余额";
                    } else {
                        CashLog cash = new CashLog {
                            CashNo = $"CN-{DateTime.Now.ToString("yyyyMMdd")}-{BaseCode.GetRandomCode(5)}",
                            UserId = user.Id,
                            Price = price,
                            Handlingfee = fee,
                            RealPrice = realPrice,
                            CreateTime = DateTime.Now,
                            Status = CashStatus.未处理
                        };

                        await context.CashLogs.AddAsync(cash);


                        await context.Incomes.AddAsync(new IncomeInfo {
                            CreateTime = DateTime.Now,
                            IncomePrice = cash.RealPrice,
                            Remark = $"申请提现，单号:{cash.CashNo}",
                            SystemType = SystemType.支出,
                            UserId = user.Id,
                            UserName = user.UserName,
                            SourceId = cash.CashNo
                        });

                        user.Overage -= realPrice;
                        context.Users.Update(user);

                        var i = await context.SaveChangesAsync();

                        if (i > 0) {
                            res.code = 0;
                            res.message = "申请成功";
                            res.data = user.Overage.ToString("C");
                        } else {
                            res.code = 2001;
                            res.message = "申请失败";
                        }
                    }
                } else {
                    res.code = 2001;
                    res.message = "您输入的二级密码无效，请重新输入";
                }
            }

            return Ok(res);
        }

        public async Task<IActionResult> GetUserCashInfo(long Id) {
            Result result = new Result();
            using (var context = new SqlServerDB()) {
                var user = await context.Users.FirstOrDefaultAsync(m => m.Id == Id);

                await context.Entry(user).Collection(u => u.Cash).Query().FirstOrDefaultAsync();

                if (user != null && user.Cash != null && user.Cash.Count > 0) {
                    var cash = user.Cash.FirstOrDefault();
                    result.data = new {
                        bank = cash.Bank,
                        account = cash.Account,
                        name = cash.AccountName,
                        strCashType = cash.CashType.ToString(),
                        cashType = (int)cash.CashType
                    };
                } else {
                    result.code = 2001;
                    result.message = "非法操作";
                }
            }

            return Ok(result);
        }
        #endregion

        #region Product
        public async Task<IActionResult> SaveProduct([FromBody]ProductInfo model) {
            Result result = new Result();

            using (var context = new SqlServerDB()) {
                var oldModel = await context.Products.FirstOrDefaultAsync();

                if (oldModel != null) {
                    oldModel.ImgUrl = model.ImgUrl;
                    oldModel.Content = model.Content;
                    oldModel.Name = model.Name;
                    oldModel.Price = model.Price;
                } else {
                    await context.Products.AddAsync(model);
                }

                var i = await context.SaveChangesAsync();

                if (i > 0) {
                    result.code = 0;
                    result.message = "保存成功";
                } else {
                    result.code = 2001;
                    result.message = "保存失败";
                }
            }

            return Ok(result);
        }
        #endregion

        #region Order
        public async Task<IActionResult> SaveOrder([FromBody]OrderInfos order) {
            Result result = new Result();

            long id = 0;
            string strId = HttpContext.User.Identity.GetValue(ClaimTypes.Sid);
            long.TryParse(strId, out id);

            using (var context = new SqlServerDB()) {
                order.CreateTime = DateTime.Now;
                order.UserId = id;
                order.AllPrice = order.Price * order.Count;
                order.OrderNo = $"OD-{DateTime.Now.ToString("yyyyMMddHH")}-{BaseCode.GetRandomCode(5)}";
                order.RemittanceBank = "";
                order.RemittanceNo = "";
                order.RemittanceTime = DateTime.Now;

                if ((order.RemittanceImg + "").Length == 0) {
                    order.Status = OrderStatus.未汇款;
                } else {
                    order.Status = OrderStatus.已汇款;
                }

                await context.Orders.AddAsync(order);

                var i = await context.SaveChangesAsync();

                if (i > 0) {
                    result.code = 0;
                    result.message = "购买成功";
                } else {
                    result.code = 2001;
                    result.message = "购买失败";
                }
            }

            return Ok(result);
        }

        public async Task<IActionResult> OrderList(int userType, int page, int limit, string userCode, string phone, int status, string userName, int userId = 0) {
            using (var context = new SqlServerDB()) {
                page--;
                IQueryable<OrdersInfoExt> queryable;

                queryable = from o in context.Orders
                            join u in context.Users on o.UserId equals u.Id
                            orderby o.Status, o.Id descending
                            select new OrdersInfoExt {
                                Id = o.Id,
                                UserId = o.UserId,
                                OrderNo = o.OrderNo,
                                ProductName = o.ProductName,
                                Receiver = o.Receiver,
                                Address = o.Address,
                                Phone = o.Phone,
                                Count = o.Count,
                                AllPrice = o.AllPrice,
                                CreateTime = o.CreateTime,
                                Remittance = o.Remittance,
                                RemittanceBank = o.RemittanceBank,
                                RemittanceNo = o.RemittanceNo,
                                RemittanceTime = o.RemittanceTime,
                                RemittanceImg = o.RemittanceImg,
                                Status = o.Status,
                                UserCode = u.UserCode,
                                UserName = u.UserName
                            };

                if (userId > 0) {
                    queryable = queryable.Where(w => w.UserId == userId);
                }

                if ((userCode + "").Length > 0) {
                    queryable = queryable.Where(w => w.UserCode.Contains(userCode));
                }

                if ((userName + "").Length > 0) {
                    queryable = queryable.Where(w => w.UserName.Contains(userName));
                }

                if (status > 0) {
                    queryable = queryable.Where(w => (int)w.Status == status);
                }

                List<OrdersInfoExt> list = await queryable.ToListAsync();

                int count = list.Count;

                return Ok(new {
                    code = 0,
                    msg = "",
                    count,
                    data = list.Skip(page * limit).Take(limit).ToJsonString()
                });
            }
        }


        public async Task<IActionResult> DelOrder(string ids) {
            Result result = new Result();

            using (var context = new SqlServerDB()) {
                if (ids.Length > 0) {
                    List<long> idList = new List<long>();
                    string[] idArray = ids.Split(',');
                    long id = 0;

                    foreach (var i in idArray) {
                        if (long.TryParse(i, out id)) {
                            if (id > 1) {
                                idList.Add(id);
                            }
                        }
                    }

                    if (idList.Count > 0) {
                        var list = context.Orders.Where(m => idList.Contains(m.Id));

                        if (list.Count() > 0) {
                            await list.ForEachAsync(m => m.Status = OrderStatus.已取消);

                            context.Orders.UpdateRange(list);

                            int flag = await context.SaveChangesAsync();

                            if (flag > 0) {
                                result.code = 0;
                                result.success = true;
                                result.message = "取消成功";
                            } else {
                                result.code = 1002;
                                result.success = true;
                                result.message = "取消失败，请稍候重试";
                            }

                            return Ok(result);
                        }
                    }
                }
            }


            result.code = 1001;
            result.success = true;
            result.message = "未选择要删除的数据";

            return Ok(result);
        }

        public async Task<IActionResult> SaveRemittance([FromBody]OrderInfos order) {
            Result result = new Result();
            using (var context = new SqlServerDB()) {
                var model = await context.Orders.FirstOrDefaultAsync(f => f.Id == order.Id);

                if (model != null) {
                    model.Remittance = order.Remittance;
                    model.RemittanceBank = order.RemittanceBank == null ? "" : order.RemittanceBank;
                    model.RemittanceNo = order.RemittanceNo == null ? "" : order.RemittanceNo;
                    model.RemittanceImg = order.RemittanceImg;
                    model.RemittanceTime = DateTime.Now;
                    model.Status = OrderStatus.已汇款;

                    context.Orders.Update(model);

                    int flag = await context.SaveChangesAsync();

                    if (flag > 0) {
                        result.code = 0;
                        result.success = true;
                        result.message = "保存成功";
                    } else {
                        result.code = 1002;
                        result.success = true;
                        result.message = "保存失败，请稍候重试";
                    }

                    return Ok(result);
                }
            }

            result.code = 1001;
            result.success = true;
            result.message = "非法操作";

            return Ok(result);
        }

        public async Task<IActionResult> SaveExpress([FromBody]ExpressInfo express) {
            Result result = new Result();
            using (var context = new SqlServerDB()) {
                using (var trans = context.Database.BeginTransaction()) {
                    try {
                        var order = await context.Orders.FirstOrDefaultAsync(m => m.Id == express.Id);

                        var admin = await context.Users.FirstOrDefaultAsync(m => m.UserType == UserTypes.超级管理员);

                        await context.Entry(order).Collection(o => o.ExpressInfos).Query().ToListAsync();

                        if (order.ExpressInfos == null) order.ExpressInfos = new List<ExpressInfo>();

                        Users parent = null;

                        order.ExpressInfos.Add(new ExpressInfo {
                            ExpressName = express.ExpressName,
                            Mailno = express.Mailno,
                            CreateTime = DateTime.Now
                        });

                        //订单已汇款的走未发货流程，其它则直接添加快递记录
                        if (order.Status == OrderStatus.已汇款 || order.Status == OrderStatus.未汇款) {
                            order.Status = OrderStatus.已发货;
                            context.Orders.Update(order);

                            var user = await DevelopDividendAsync(context, order.UserId, admin, order.OrderNo); //开发将并返回用户信息

                            if (user != null) {
                                await context.Incomes.AddAsync(new IncomeInfo {
                                    SystemType = SystemType.收入,
                                    IncomePrice = order.AllPrice,
                                    Remark = $"会员{user.UserName}购买商品，来源订单编号：{order.OrderNo}",
                                    UserId = admin.Id,
                                    UserName = admin.UserName,
                                    SourceId = order.OrderNo
                                });

                                if (user.Level == LevelCode.未激活) {//如果是未激活则获取上级的用户进行团队分红
                                    parent = await context.Users.FirstOrDefaultAsync(m => m.Id == user.ParentId && m.IsEnable);
                                } else {//如果不是则将当前购买用户当成自己的上级
                                    parent = user;
                                }

                                if (parent != null) {
                                    var sameLevelCount = await context.Settings.FirstOrDefaultAsync(m => m.SystemType == SystemType.同级奖励
                                                                                && m.OtherType == ((int)SystemType.同级奖励分配人数).ToString());

                                    int count = 0;

                                    if (sameLevelCount != null) {
                                        int.TryParse(sameLevelCount.Values, out count);
                                    }

                                    await DividendAsync(context, parent, admin, 0, count, order.OrderNo); //团队分红并执行相应的同级奖励
                                }

                                await CityDividendAsync(context, order.CityId, admin, order.OrderNo); //城市管理,大区分红

                                await ProvinceDividendAsync(context, order.ProvinceId, admin, order.OrderNo); //省级分红

                                await LifeLongDividendAsync(context, admin, order.Count, order.OrderNo); //终身分红

                                await LevelUp(context, user, order.AllPrice, order.Count); //用户升级
                            } else {
                                trans.Rollback();
                                result.code = 1002;
                                result.success = true;
                                result.message = "用户不存在";

                                return Ok(result);
                            }
                        } else {
                            context.Orders.Update(order);
                        }

                        int flag = await context.SaveChangesAsync();

                        trans.Commit();

                        if (flag > 0) {
                            result.code = 0;
                            result.success = true;
                            result.message = "保存成功";
                        } else {
                            result.code = 1002;
                            result.success = true;
                            result.message = "保存失败，请稍候重试";
                        }
                    } catch (Exception ex) {
                        trans.Rollback();
                        result.code = 1002;
                        result.success = true;
                        result.message = ex.InnerException != null ? ex.InnerException.Message : ex.Message;
                    }

                    return Ok(result);
                }
            }
        }

        private async Task LevelUp(SqlServerDB context, Users user, decimal allPrice, int buyCount, List<SystemSetting> LevelUps = null) {
            if (LevelUps == null) LevelUps = await context.Settings.Where(m => m.SystemType == SystemType.升级条件).ToListAsync();

            if (LevelUps.Count > 0) {
                if (user.Level > LevelCode.全国总代) {
                    var luModel = LevelUps.FirstOrDefault(m => m.OtherType == ((int)user.Level).ToString());

                    if (luModel != null) {
                        var parent = await context.Users.FirstOrDefaultAsync(m => m.Id == user.ParentId && m.IsEnable);

                        if (user.Level == LevelCode.未激活) {
                            decimal.TryParse(luModel.Values, out decimal levelPrice);

                            if (allPrice >= levelPrice) {
                                user.Level = user.Level - 1;
                            }
                        } else {
                            var levelOther = await context.Settings.FirstOrDefaultAsync(m => m.SystemType == SystemType.升级基数
                                                                                            && m.OtherType == ((int)user.Level).ToString());

                            int.TryParse(luModel.Values, out int levelCount);//升级条件
                            int.TryParse(levelOther.Values, out int levelCN);//升级基数
                            int orderCount = await context.Orders.Where(m => m.UserId == user.Id
                                                                                    && m.Status == OrderStatus.已发货).SumAsync(m => m.Count);
                            int subordinateCount = await context.Users.CountAsync(m => m.ParentId == user.Id
                                                                                            && m.IsEnable);

                            var result = subordinateCount + (orderCount + buyCount) / levelCN;

                            if (result >= levelCount) {
                                user.Level = user.Level - 1;

                                if (parent != null) {
                                    if (parent.Level > user.Level) {//插入感恩回馈表
                                        if (await context.LevelUpLogs.CountAsync(m => m.UserId == user.Id) == 0) {
                                            if (await context.Settings.CountAsync(m => m.SystemType == SystemType.感恩分红 && m.OtherType == ((int)user.Level).ToString()) > 0) {
                                                await context.LevelUpLogs.AddAsync(new LevelUpLog {
                                                    UserId = user.Id,
                                                    Level = user.Level,
                                                    CreateTime = DateTime.Now,
                                                    IsEnable = true
                                                });
                                            }
                                        }
                                    }
                                }
                            }
                        }

                        context.Users.Update(user);

                        if (parent != null) {
                            await LevelUp(context, parent, 0, 0, LevelUps);
                        }
                    }
                }
            }
        }

        /// <summary>
        /// 终身分红
        /// </summary>
        /// <param name="context"></param>
        /// <param name="admin"></param>
        /// <returns></returns>
        private async Task LifeLongDividendAsync(SqlServerDB context, Users admin, int orderCount, string orderNo) {
            var lifeLongGens = await context.Users.Where(m => m.Level == LevelCode.全国总代 && m.IsEnable).ToListAsync();
            List<IncomeInfo> list = new List<IncomeInfo>();

            if (lifeLongGens != null && lifeLongGens.Count > 0) {
                int count = lifeLongGens.Count();

                var lifelong = await context.Settings.FirstOrDefaultAsync(m => m.SystemType == SystemType.终身分红);

                decimal.TryParse(lifelong.Values, out decimal dividend);

                dividend = (dividend * orderCount) / count;

                foreach (var m in lifeLongGens) {
                    m.Overage += dividend;

                    list.Add(new IncomeInfo {
                        SystemType = SystemType.收入,
                        IncomePrice = dividend,
                        Remark = SystemType.终身分红.ToString(),
                        UserId = m.Id,
                        UserName = m.UserName,
                        SourceId = orderNo
                    });
                    list.Add(new IncomeInfo {
                        SystemType = SystemType.支出,
                        IncomePrice = dividend,
                        Remark = SystemType.终身分红.ToString(),
                        UserId = admin.Id,
                        UserName = admin.UserName,
                        SourceId = orderNo
                    });

                    await GratefulDividendAsync(m, admin, context, null, dividend, null, -1, orderNo);
                }

                context.Users.UpdateRange(lifeLongGens);
                await context.Incomes.AddRangeAsync(list);
            }
        }

        /// <summary>
        /// 省级分红
        /// </summary>
        /// <param name="context"></param>
        /// <param name="provinceId"></param>
        /// <param name="admin"></param>
        /// <returns></returns>
        private async Task ProvinceDividendAsync(SqlServerDB context, int provinceId, Users admin, string orderNo) {
            var proGen = await context.Users.FirstOrDefaultAsync(m => m.ProvinceId == provinceId && m.IsEnable);
            List<IncomeInfo> list = new List<IncomeInfo>();

            if (proGen != null) {
                var province = await context.Settings.FirstOrDefaultAsync(m => m.SystemType == SystemType.省级分红);

                if (province != null) {
                    decimal.TryParse(province.Values, out decimal dividend);
                    proGen.Overage += dividend;

                    context.Users.Update(proGen);

                    list.Add(new IncomeInfo {
                        SystemType = SystemType.收入,
                        IncomePrice = dividend,
                        Remark = SystemType.省级分红.ToString(),
                        UserId = proGen.Id,
                        UserName = proGen.UserName,
                        SourceId = orderNo
                    });
                    list.Add(new IncomeInfo {
                        SystemType = SystemType.支出,
                        IncomePrice = dividend,
                        Remark = SystemType.省级分红.ToString(),
                        UserId = admin.Id,
                        UserName = admin.UserName,
                        SourceId = orderNo
                    });

                    await context.Incomes.AddRangeAsync(list);

                    await GratefulDividendAsync(proGen, admin, context, null, dividend, null, -1, orderNo);
                }
            }
        }

        /// <summary>
        /// 城市管理
        /// </summary>
        /// <param name="context"></param>
        /// <param name="cityId"></param>
        /// <param name="admin"></param>
        /// <returns></returns>
        private async Task CityDividendAsync(SqlServerDB context, int cityId, Users admin, string orderNo) {
            var cityGen = await context.Users.FirstOrDefaultAsync(m => m.CityId == cityId && m.IsEnable);
            List<IncomeInfo> list = new List<IncomeInfo>();
            if (cityGen != null) {
                decimal dividend = 0;
                var city = await context.Settings.FirstOrDefaultAsync(m => m.SystemType == SystemType.城市管理);

                if (city != null) {
                    decimal.TryParse(city.Values, out dividend);
                    cityGen.Overage += dividend;

                    list.Add(new IncomeInfo {
                        SystemType = SystemType.收入,
                        IncomePrice = dividend,
                        Remark = SystemType.城市管理.ToString(),
                        UserId = cityGen.Id,
                        UserName = cityGen.UserName,
                        SourceId = orderNo
                    });
                    list.Add(new IncomeInfo {
                        SystemType = SystemType.支出,
                        IncomePrice = dividend,
                        Remark = SystemType.城市管理.ToString(),
                        UserId = admin.Id,
                        UserName = admin.UserName,
                        SourceId = orderNo
                    });

                    context.Users.Update(cityGen);

                    //获得开发奖的推荐用户获得感恩分红
                    await GratefulDividendAsync(cityGen, admin, context, null, dividend, null, -1, orderNo);

                    //获取该市代的上级是否为大区代或以上
                    await RegionGenDividendAsync(context, admin, cityGen, orderNo);

                    await context.Incomes.AddRangeAsync(list);
                }
            }
        }

        /// <summary>
        /// 大区分红
        /// </summary>
        /// <param name="context"></param>
        /// <param name="admin"></param>
        /// <param name="cityGen"></param>
        /// <param name="orderNo"></param>
        /// <param name="regionGen"></param>
        /// <returns></returns>
        private async Task RegionGenDividendAsync(SqlServerDB context, Users admin, Users cityGen, string orderNo, Users regionGen = null) {
            List<IncomeInfo> list = new List<IncomeInfo>();
            decimal dividend = 0;
            if (regionGen == null) {
                regionGen = await context.Users.FirstOrDefaultAsync(m => m.Id == cityGen.ParentId && m.IsEnable);
            }

            if (regionGen != null && regionGen.Level <= LevelCode.市代 && regionGen.Level <= cityGen.Level) {
                dividend = 0;

                //获取下属市代人数
                int subordinateCount = await context.Users.CountAsync(m => m.ParentId == regionGen.Id && m.Level <= LevelCode.市代 && m.IsEnable);

                if (regionGen.Level < LevelCode.市代) { //已升级为大区代
                    var region = await context.Settings.FirstOrDefaultAsync(m => m.SystemType == SystemType.大区分红 && m.OtherType == ((int)LevelCode.大区总代).ToString());

                    if (region != null) {
                        decimal.TryParse(region.Values, out dividend);
                        regionGen.Overage += dividend;
                    }
                } else if (regionGen.Level == LevelCode.市代) { //市代下属未升级大区代
                    var levelFactor = await context.Settings.FirstOrDefaultAsync(m => m.SystemType == SystemType.升级条件 && m.OtherType == ((int)LevelCode.大区总代).ToString());

                    int.TryParse(levelFactor.Values, out int factorCount);

                    if (subordinateCount > 0 && subordinateCount <= factorCount) {//必须满路市代下属有1到小于升级条件的市代理
                        var notFull = await context.Settings.FirstOrDefaultAsync(m => m.SystemType == SystemType.大区分红 && m.OtherType == ((int)SystemType.大区分红人数未满).ToString());

                        if (notFull != null) {
                            decimal.TryParse(notFull.Values, out dividend);
                            regionGen.Overage += dividend;
                        }
                    }
                }

                if (dividend > 0) {
                    context.Users.Update(regionGen);

                    list.Add(new IncomeInfo {
                        SystemType = SystemType.收入,
                        IncomePrice = dividend,
                        Remark = SystemType.大区分红.ToString(),
                        UserId = regionGen.Id,
                        UserName = regionGen.UserName,
                        SourceId = orderNo
                    });
                    list.Add(new IncomeInfo {
                        SystemType = SystemType.支出,
                        IncomePrice = dividend,
                        Remark = SystemType.大区分红.ToString(),
                        UserId = admin.Id,
                        UserName = admin.UserName,
                        SourceId = orderNo
                    });

                    await context.Incomes.AddRangeAsync(list);

                    await GratefulDividendAsync(regionGen, admin, context, null, dividend, null, -1, orderNo);
                }
            }
        }

        /// <summary>
        /// 开发奖
        /// </summary>
        /// <param name="context"></param>
        /// <param name="userId"></param>
        /// <returns></returns>
        private async Task<Users> DevelopDividendAsync(SqlServerDB context, long userId, Users admin, string orderNo) {
            var user = await context.Users.FirstOrDefaultAsync(m => m.Id == userId && m.IsEnable);
            string strDividend = "";
            Users parent = null;
            SystemSetting develop = null;

            if (user.ParentId > 0) {
                parent = await context.Users.FirstOrDefaultAsync(m => m.Id == user.ParentId && m.IsEnable);
            }

            if (user != null && user.Level != LevelCode.未激活) {//非未激活用户获取开发奖
                develop = await context.Settings.FirstOrDefaultAsync(m => m.SystemType == SystemType.开发奖
                                                                            && m.OtherType == ((int)user.Level).ToString());
                parent = user;
            } else if (parent != null) {//未激活用户获取开发奖
                develop = await context.Settings.FirstOrDefaultAsync(m => m.SystemType == SystemType.开发奖
                                                                            && m.OtherType == ((int)parent.Level).ToString());
            }

            if (develop != null) {
                strDividend = develop.Values;

                decimal.TryParse(strDividend, out decimal dividend);

                if (dividend > 0) {
                    parent.Overage += dividend;

                    context.Users.Update(parent);

                    List<IncomeInfo> list = new List<IncomeInfo> {
                            new IncomeInfo {
                                SystemType = SystemType.收入,
                                IncomePrice = dividend,
                                Remark = SystemType.开发奖.ToString(),
                                UserId = parent.Id,
                                UserName = parent.UserName,
                                SourceId = orderNo
                            },
                            new IncomeInfo {
                                SystemType = SystemType.支出,
                                IncomePrice = dividend,
                                Remark = SystemType.开发奖.ToString(),
                                UserId = admin.Id,
                                UserName = admin.UserName,
                                SourceId = orderNo
                            }
                        };

                    await context.Incomes.AddRangeAsync(list);

                    //获得开发奖的推荐用户获得感恩分红
                    await GratefulDividendAsync(parent, admin, context, null, dividend, null, -1, orderNo);
                }
            }
            return user;
        }

        /// <summary>
        /// 团队分红
        /// </summary>
        /// <param name="context"></param>
        /// <param name="user"></param>
        /// <param name="dividend"></param>
        /// <param name="teams">团队分红列表</param>
        /// <param name="LevelCodeList">用户等级列表</param>
        /// <param name="userIds">未分配同级奖励用户</param>
        /// <returns></returns>
        private async Task<bool> DividendAsync(SqlServerDB context, Users user, Users admin, decimal dividend, int sameCount, string orderNo,
                                    List<SystemSetting> teams = null, List<Users> sameLevelUser = null,
                                    bool IsSameLevel = false, List<SystemSetting> sameLevelSetting = null) {
            try {

                var parent = await context.Users.FirstOrDefaultAsync(m => m.Id == user.ParentId && m.IsEnable);

                if (parent != null) {
                    if (teams == null) teams = await context.Settings.Where(m => m.SystemType == SystemType.团队分红).ToListAsync();

                    //正常情况
                    if (user.Level > parent.Level) {//购买会员等级比推荐人等级低
                        var team = teams.FirstOrDefault(m => m.OtherType == ((int)parent.Level).ToString());

                        decimal.TryParse(team.Values, out dividend);

                        //获取比当前等级低的团队奖励
                        teams.ForEach(m => {
                            decimal temp = 0;
                            int.TryParse(m.OtherType, out int otherType);

                            if (otherType > (int)parent.Level && otherType < (int)user.Level) {//获取推荐人等级比奖励等级低的奖励
                                decimal.TryParse(m.Values, out temp);

                                dividend += temp;
                            }
                        });

                        parent.Overage += dividend;

                        context.Users.Update(parent);

                        await context.Incomes.AddRangeAsync(new List<IncomeInfo>{
                            new IncomeInfo {
                                SystemType = SystemType.收入,
                                IncomePrice = dividend,
                                Remark = SystemType.团队分红.ToString(),
                                UserId = parent.Id,
                                UserName = parent.UserName,
                                SourceId = orderNo
                            },
                            new IncomeInfo {
                                SystemType = SystemType.支出,
                                IncomePrice = dividend,
                                Remark = SystemType.团队分红.ToString(),
                                UserId = admin.Id,
                                UserName = admin.UserName,
                                SourceId = orderNo
                            }
                        });

                        //团队分红的该用户上级可能需要走感恩分红
                        await GratefulDividendAsync(parent, admin, context, null, dividend, null, -1, orderNo);

                        if (parent.Level == LevelCode.全国总代) {
                            if (sameLevelUser.Count > 0) {
                                var levels = sameLevelUser.GroupBy(m => m.Level).Select(m => m.Key).ToList();

                                foreach (var l in levels) {
                                    await SameLevelDividendAsync(sameLevelUser.FindAll(m => m.Level == l),
                                                                    admin, l, context, sameLevelSetting, orderNo);
                                }
                            }

                            return true;
                        }
                    } else if (user.Level == parent.Level) {//此处走同级逻辑
                        if (sameLevelSetting == null) sameLevelSetting = await context.Settings.Where(m => m.SystemType == SystemType.同级奖励).ToListAsync();

                        if (sameLevelSetting != null && sameLevelSetting.Count > 0) {
                            if (sameLevelSetting.Count(m => m.OtherType == ((int)parent.Level).ToString()) > 0) {//判断当前用户是否有同步奖励
                                if (sameLevelUser == null) sameLevelUser = new List<Users>();

                                if (sameLevelUser.Count(m => m.Level == parent.Level) < sameCount) {
                                    sameLevelUser.Add(parent);
                                }

                                //if (sameLevelUser.Count(m => m.Level == LevelCode.区代) < sameCount) {
                                //    sameLevelUser.Add(parent);
                                //}
                            }
                        }
                    }

                    return await DividendAsync(context, parent, admin, 0, sameCount, orderNo, teams, sameLevelUser, true, sameLevelSetting);
                }

                //上级非全国总代的逻辑
                if (sameLevelUser.Count > 0) {
                    var levels = sameLevelUser.GroupBy(m => m.Level).Select(m => m.Key).ToList();

                    foreach (var l in levels) {
                        await SameLevelDividendAsync(sameLevelUser.FindAll(m => m.Level == l),
                                                        admin, l, context, sameLevelSetting, orderNo);
                    }
                }
            } catch (Exception ex) {
                return false;
            }

            return true;
        }

        /// <summary>
        /// 同级奖励
        /// </summary>
        /// <param name="userList"></param>
        /// <param name="admin"></param>
        /// <param name="level"></param>
        /// <param name="context"></param>
        /// <returns></returns>
        private async Task SameLevelDividendAsync(List<Users> userList, Users admin, LevelCode level, SqlServerDB context, List<SystemSetting> sameLevelList, string orderNo) {
            if (userList != null && userList.Count > 0) {
                var sameLevel = sameLevelList.FirstOrDefault(m => m.OtherType == ((int)level).ToString());

                if (sameLevel != null) {
                    decimal.TryParse(sameLevel.Values, out decimal allDividend);

                    decimal dividend = allDividend / userList.Count;
                    List<IncomeInfo> iList = new List<IncomeInfo>();
                    userList.ForEach(m => {
                        m.Overage += dividend;

                        iList.Add(new IncomeInfo {
                            SystemType = SystemType.收入,
                            IncomePrice = dividend,
                            Remark = SystemType.同级奖励.ToString(),
                            UserId = m.Id,
                            UserName = m.UserName,
                            SourceId = orderNo
                        });

                        iList.Add(new IncomeInfo {
                            SystemType = SystemType.支出,
                            IncomePrice = dividend,
                            Remark = SystemType.同级奖励.ToString(),
                            UserId = admin.Id,
                            UserName = admin.UserName,
                            SourceId = orderNo
                        });
                    });

                    context.Users.UpdateRange(userList);
                    await context.Incomes.AddRangeAsync(iList);

                    //同级奖励最后一人即为下一人有可能需要获得感恩分红
                    await GratefulDividendAsync(userList.LastOrDefault(), admin, context, null, dividend, null, -1, orderNo);
                }
            }
        }

        /// <summary>
        /// 感恩分红
        /// </summary>
        /// <param name="user"></param>
        /// <param name="admin"></param>
        /// <param name="context"></param>
        /// <param name="gratefulList"></param>
        /// <param name="incomePrice"></param>
        /// <param name="gratefulLong"></param>
        /// <param name="gratefulDay"></param>
        /// <returns></returns>
        private async Task<bool> GratefulDividendAsync(Users user, Users admin, SqlServerDB context, List<SystemSetting> gratefulList,
                                                                    decimal incomePrice, SystemSetting gratefulLong, int gratefulDay, string orderNo) {
            try {
                var parent = await context.Users.FirstOrDefaultAsync(m => m.Id == user.ParentId && m.IsEnable);

                if (parent != null) {
                    if (parent.Level > user.Level) {//这里走的是感恩分红
                        if (gratefulList == null) gratefulList = await context.Settings.Where(m => m.SystemType == SystemType.感恩分红).ToListAsync();
                        if (gratefulLong == null) gratefulLong = gratefulList.FirstOrDefault(m => m.OtherType == ((int)SystemType.永久奖励).ToString());

                        decimal dividend = 0;

                        if (gratefulLong != null) {
                            decimal.TryParse(gratefulLong.Values, out dividend);
                        }

                        if (gratefulDay == -1) {
                            var settingDay = await context.Settings.FirstOrDefaultAsync(m => m.SystemType == SystemType.感恩分红最大天数);

                            int.TryParse(settingDay.Values, out gratefulDay);
                        }

                        if (gratefulDay > 0) {
                            var logs = await context.LevelUpLogs.FirstOrDefaultAsync(m => m.UserId == user.Id && m.IsEnable);

                            if (logs != null) {
                                TimeSpan ts = DateTime.Now - logs.CreateTime;

                                if (gratefulDay > ts.Days) {
                                    var g = gratefulList.FirstOrDefault(m => m.OtherType == ((int)logs.Level).ToString()); //获取当前被推荐人能给与推荐人的感恩分红奖励信息

                                    if (g != null) {
                                        var strPer = g.Values;
                                        decimal Per = 0;
                                        if (strPer.LastIndexOf("%") > -1) {
                                            int.TryParse(strPer.Replace("%", ""), out int intPer);
                                            Per = intPer / 100;
                                        } else {
                                            decimal.TryParse(strPer, out Per);
                                        }

                                        dividend += incomePrice * Per;
                                    }
                                } else {
                                    logs.IsEnable = false;
                                    context.LevelUpLogs.Update(logs);
                                }
                            }
                        }

                        parent.Overage += dividend;
                        context.Users.Update(parent);
                        await context.Incomes.AddRangeAsync(new List<IncomeInfo>{
                            new IncomeInfo {
                                SystemType = SystemType.收入,
                                IncomePrice = dividend,
                                Remark = SystemType.感恩分红.ToString(),
                                UserId = parent.Id,
                                UserName = parent.UserName,
                                SourceId = orderNo
                            },
                            new IncomeInfo {
                                SystemType = SystemType.支出,
                                IncomePrice = dividend,
                                Remark = SystemType.感恩分红.ToString(),
                                UserId = admin.Id,
                                UserName = admin.UserName,
                                SourceId = orderNo
                            }
                        });

                        return await GratefulDividendAsync(parent, admin, context, gratefulList, dividend, gratefulLong, gratefulDay, orderNo);
                    }

                    return true;
                }
            } catch (Exception ex) {
                return false;
            }

            return true;
        }

        public IActionResult OrderInfo(long Id) {
            OrdersInfoExt ext = new OrdersInfoExt();
            try {
                using (var context = new SqlServerDB()) {
                    var order = context.Orders.FirstOrDefault(m => m.Id == Id);

                    if (order != null) {
                        context.Entry(order).Collection(o => o.ExpressInfos).Query().OrderByDescending(o => o.Id).ToList();
                        var user = context.Users.FirstOrDefault(m => m.Id == order.UserId);

                        ext.Id = order.Id;
                        ext.OrderNo = order.OrderNo;
                        ext.Phone = order.Phone;
                        ext.UserName = user.UserName;
                        ext.UserCode = user.UserCode;
                        ext.ExpressInfos = order.ExpressInfos;
                        ext.Address = order.Address;
                        ext.AllPrice = order.AllPrice;
                        ext.Count = order.Count;
                        ext.ProductName = order.ProductName;
                        ext.Receiver = order.Receiver;
                        ext.Remittance = order.Remittance;
                        ext.RemittanceBank = order.RemittanceBank;
                        ext.RemittanceNo = order.RemittanceNo;
                        ext.RemittanceTime = order.RemittanceTime;
                        ext.RemittanceImg = order.RemittanceImg;
                        ext.Status = order.Status;
                        ext.UserId = order.UserId;
                    }

                    return Ok(ext.ToJsonString());
                }
            } catch (Exception ex) {
                return Ok(ex.InnerException != null ? ex.InnerException.Message : ex.Message);
            }
        }

        #endregion

        #region Finance
        public async Task<IActionResult> IncomeList(int userType, int page, int limit, int type, int userId = 0, int id = 0) {
            using (var context = new SqlServerDB()) {
                page--;

                IQueryable<IncomeInfo> queryable;

                if (id == 0) {
                    if (userType == (int)UserTypes.普通用户) {
                        queryable = context.Incomes.Where(m => m.UserId == userId);
                    } else {
                        var user = await context.Users.FirstOrDefaultAsync(m => m.UserType == UserTypes.超级管理员);

                        queryable = context.Incomes.Where(m => m.UserId == user.Id);
                    }
                } else {
                    queryable = context.Incomes.Where(m => m.UserId == id);
                }

                if (type > 0) {
                    queryable = queryable.Where(m => (int)m.SystemType == type);
                }

                List<IncomeInfo> uList = await queryable.OrderByDescending(m => m.Id).ToListAsync();


                int count = uList.Count();

                return Ok(new {
                    code = 0,
                    msg = "",
                    count,
                    data = uList.Skip(page * limit).Take(limit).ToJsonString()
                });
            }
        }

        public async Task<IActionResult> CashLogsList(string userName, int page, int limit, int status, int userId = 0) {
            using (var context = new SqlServerDB()) {
                page--;

                IQueryable<CashLog> queryable = from c in context.CashLogs select c;

                if (userId > 0) {
                    queryable = context.CashLogs.Where(m => m.UserId == userId);
                }

                if (status > 0) {
                    queryable = queryable.Where(m => (int)m.Status == status);
                }

                var uList = await (from c in queryable
                                   join u in context.Users on c.UserId equals u.Id
                                   orderby c.Status, c.Id descending
                                   select new {
                                       c.Id,
                                       c.CreateTime,
                                       c.CashNo,
                                       c.Handlingfee,
                                       c.Price,
                                       c.strPrice,
                                       c.RealPrice,
                                       c.strFee,
                                       c.strRealPrice,
                                       c.strStatus,
                                       c.Status,
                                       c.UserId,
                                       UserName = $"{u.UserName}（{u.UserCode}）"
                                   }).ToListAsync();


                int count = uList.Count();

                return Ok(new {
                    code = 0,
                    msg = "",
                    count,
                    data = uList.Skip(page * limit).Take(limit).ToJsonString()
                });
            }
        }

        public async Task<IActionResult> ChangeCashLog([FromBody]Dictionary<string, object> data) {
            Result res = new Result();

            using (var context = new SqlServerDB()) {
                using (var trans = context.Database.BeginTransaction()) {
                    try {
                        long Id = Convert.ToInt64(data.GetValueOrDefault("id", 0));

                        CashStatus status = (CashStatus)Convert.ToInt16(data.GetValueOrDefault("status", 0));

                        var cashlog = await context.CashLogs.FirstOrDefaultAsync(m => m.Id == Id);

                        if (cashlog != null) {
                            cashlog.Status = status;

                            context.CashLogs.Update(cashlog);

                            if (cashlog.Status == CashStatus.取消) {
                                var user = await context.Users.FirstOrDefaultAsync(m => m.Id == cashlog.UserId);

                                if (user != null) {
                                    user.Overage += cashlog.RealPrice;

                                    context.Users.Update(user);

                                    await context.Incomes.AddAsync(new IncomeInfo {
                                        CreateTime = DateTime.Now,
                                        IncomePrice = cashlog.RealPrice,
                                        Remark = "提现被驳回",
                                        SystemType = SystemType.收入,
                                        UserId = user.Id,
                                        UserName = user.UserName,
                                        SourceId = cashlog.CashNo
                                    });
                                }
                            }

                            var i = await context.SaveChangesAsync();
                            trans.Commit();

                            if (i > 0) {
                                res.code = 0;
                                res.message = "操作成功";
                            } else {
                                res.code = 2001;
                                res.message = "操作失败";
                            }
                        }
                    } catch (Exception ex) {
                        trans.Rollback();
                        res.code = 2001;
                        res.message = $"服务器异常，异常消息：{(ex.InnerException != null ? ex.InnerException.Message : ex.Message)}";
                    }
                }
            }

            return Ok(res);
        }

        public async Task<IActionResult> GetHandlingfee() {
            Result res = new Result();

            try {
                using (var context = new SqlServerDB()) {
                    var settings = await context.Settings.Where(m => m.SystemType == SystemType.提现).ToListAsync();
                    var s = settings.FirstOrDefault(m => m.OtherType == ((int)SystemType.提现手续费).ToString());
                    var t = settings.FirstOrDefault(m => m.OtherType == ((int)SystemType.提现日期).ToString());
                    var multiple = settings.FirstOrDefault(m => m.OtherType == ((int)SystemType.提现倍数).ToString());

                    res.code = 0;
                    res.message = "";
                    res.data = new {
                        fee = s != null ? s.Values : "",
                        time = t != null ? t.Values : "",
                        multiple = multiple != null ? multiple.Values : "0"
                    };
                }
            } catch (Exception ex) {
                res.code = 2001;
                res.message = "";
            }

            return Ok(res);
        }

        public async Task<IActionResult> SetHandlingfee([FromBody]Dictionary<string, string> data) {
            Result res = new Result();
            using (var context = new SqlServerDB()) {
                var settings = await context.Settings.Where(m => m.SystemType == SystemType.提现).ToListAsync();
                var fee = data.GetValueOrDefault("fee", "");
                var time = data.GetValueOrDefault("time", "");
                var multiple = data.GetValueOrDefault("multiple", "");

                if ((fee + "").Length > 0) {
                    var s = settings.FirstOrDefault(m => m.OtherType == ((int)SystemType.提现手续费).ToString());

                    if (s != null) {
                        s.Values = fee;

                        context.Settings.Update(s);
                    } else {
                        s = new SystemSetting {
                            SystemType = SystemType.提现,
                            OtherType = ((int)SystemType.提现手续费).ToString(),
                            Values = multiple
                        };

                        await context.Settings.AddAsync(s);
                    }
                }

                if ((time + "").Length > 0) {
                    var t = settings.FirstOrDefault(m => m.OtherType == ((int)SystemType.提现日期).ToString());

                    if (t != null) {
                        t.Values = time;

                        context.Settings.Update(t);
                    } else {
                        t = new SystemSetting {
                            SystemType = SystemType.提现,
                            OtherType = ((int)SystemType.提现日期).ToString(),
                            Values = time
                        };

                        await context.Settings.AddAsync(t);
                    }
                }

                if ((multiple + "").Length > 0) {
                    var mul = settings.FirstOrDefault(m => m.OtherType == ((int)SystemType.提现倍数).ToString());

                    if (mul != null) {
                        mul.Values = multiple;

                        context.Settings.Update(mul);
                    } else {
                        mul = new SystemSetting {
                            SystemType = SystemType.提现,
                            OtherType = ((int)SystemType.提现倍数).ToString(),
                            Values = multiple
                        };

                        await context.Settings.AddAsync(mul);
                    }
                }

                var i = await context.SaveChangesAsync();

                if (i > 0) {
                    res.code = 0;
                    res.message = "操作成功";
                } else {
                    res.code = 2001;
                    res.message = "操作失败";
                }
            }

            return Ok(res);
        }
        #endregion

        #region Other
        public async Task<IActionResult> GetCityList(int id, int userId, int remove = 1) {
            Result result = new Result();

            if (id > 0) {

                CacheHelper cache = new CacheHelper();
                List<Area> area = new List<Area>();


                if (remove == 1) {
                    area = cache.GetNewAreas().Where(m => m.parent == id).ToList();

                    using (var context = new SqlServerDB()) {
                        var list = await context.Users.ToListAsync();

                        foreach (var l in list) {
                            if (l.CityId == 0) continue;

                            var a = area.FirstOrDefault(m => m.id == l.CityId && l.Id != userId);

                            area.Remove(a);
                        }
                    }
                } else {
                    area = cache.GetAreaList().Where(m => m.parent == id).ToList();
                }

                if (area.Count > 0) {
                    area.Insert(0, (new Area { id = 0, name = "请选择" }));
                }

                result.code = 0;
                result.message = "";
                result.data = area;
            }

            return Ok(result);
        }

        public async Task<IActionResult> SetAllUserTeamCount() {
            using (var context = new SqlServerDB()) {
                Result result = new Result();
                try {

                    var list = await context.Users.ToListAsync();

                    foreach (var u in list) {
                        if (u.ParentId > 0) {
                            await SetTeamCountAsync(u.ParentId, context);
                        }
                    }

                    int flag = await context.SaveChangesAsync();
                } catch (Exception ex) {
                    result.message = ex.InnerException != null ? ex.InnerException.Message : ex.Message;
                }

                return Ok(result);
            }
        }

        public async Task<IActionResult> FileSave() {
            try {
                var data = Request;
                var files = Request.Form.Files;

                FileHelper file = new FileHelper();
                string newFileName = "";

                foreach (var formFile in files) {
                    if (formFile.Length > 0) {
                        string fileExt = formFile.FileName.Substring(formFile.FileName.LastIndexOf('.'));

                        long fileSize = formFile.Length;

                        newFileName = $"p{DateTime.Now.ToString("yyyyMMddHHmmssfff")}{fileExt}";

                        await file.FileSave(formFile, newFileName);
                    }
                }

                return Ok(new {
                    code = 0,
                    msg = "",
                    data = new {
                        src = $"/uploads/{newFileName}"
                    }
                });
            } catch (Exception ex) {
                return Ok(new {
                    code = 1001,
                    msg = $"上传图片异常，异常消息：{(ex.InnerException != null ? ex.InnerException.Message : ex.Message)}"
                });
            }
        }

        public IActionResult GetUserListColumns(int userType, int isShowOverage) {
            List<Columns> list = (typeof(Users).GetColumns()).Where(m => m.show == userType || m.show == 0 || m.show == isShowOverage).ToList();


            return Ok(list);
        }

        public IActionResult GetOrderListColumns(int userType) {
            List<Columns> list = (typeof(OrdersInfoExt).GetColumns()).OrderBy(m => m.order).ToList();

            return Ok(list);
        }

        public IActionResult GetIncomeListColumns() {
            List<Columns> list = (typeof(IncomeInfo).GetColumns()).OrderBy(m => m.order).ToList();

            return Ok(list);
        }

        public IActionResult GetCashLogListColumns() {
            List<Columns> list = (typeof(CashLogExt).GetColumns()).OrderBy(m => m.order).ToList();

            return Ok(list);
        }
        public IActionResult GetNoticeListColumns() {
            List<Columns> list = (typeof(Notice).GetColumns()).OrderBy(m => m.order).ToList();

            return Ok(list);
        }
        #endregion

        #region Notice
        public async Task<IActionResult> SaveNotice([FromBody]Notice model) {
            Result result = new Result();

            using (var context = new SqlServerDB()) {
                if (model.Id == 0) {
                    if ((model.NoticeType + "").Length == 0) {
                        model.NoticeType = NoticeType.交流公告;
                    }
                    model.CreateTime = DateTime.Now;

                    await context.Notices.AddAsync(model);
                } else {
                    context.Notices.Update(model);
                }

                var i = await context.SaveChangesAsync();

                if (i > 0) {
                    result.code = 0;
                    result.message = "保存成功";
                } else {
                    result.code = 2001;
                    result.message = "保存失败";
                }
            }

            return Ok(result);
        }

        public async Task<IActionResult> NoticeList(string keyWord, int page, int limit) {
            using (var context = new SqlServerDB()) {
                page--;
                IQueryable<Notice> noticeList = context.Notices.Where(m => m.NoticeType == NoticeType.交流公告);

                if ((keyWord + "").Length > 0) {
                    noticeList = noticeList.Where(m => m.Name.Contains(keyWord) || m.Content.Contains(keyWord));
                }

                int count = await noticeList.CountAsync();

                var list = await noticeList.ToListAsync();

                return Ok(new {
                    code = 0,
                    msg = "",
                    count,
                    data = list.OrderByDescending(m => m.Id).Skip(page * limit).Take(limit).ToJsonString()
                });
            }
        }


        public async Task<IActionResult> DelNotice(string ids) {
            Result result = new Result();

            using (var context = new SqlServerDB()) {
                if (ids.Length > 0) {
                    List<long> idList = new List<long>();
                    string[] idArray = ids.Split(',');
                    long id = 0;

                    foreach (var i in idArray) {
                        if (long.TryParse(i, out id)) {
                            idList.Add(id);
                        }
                    }

                    if (idList.Count > 0) {
                        var list = context.Notices.Where(m => idList.Contains(m.Id));

                        if (list.Count() > 0) {
                            context.Notices.RemoveRange(list);

                            int flag = await context.SaveChangesAsync();

                            if (flag > 0) {
                                result.code = 0;
                                result.success = true;
                                result.message = "删除成功";
                            } else {
                                result.code = 1002;
                                result.success = true;
                                result.message = "删除失败，请稍候重试";
                            }

                            return Ok(result);
                        }
                    }
                }
            }


            result.code = 1001;
            result.success = true;
            result.message = "删除失败，请稍候重试";

            return Ok(result);
        }
        #endregion

        #region ECharts
        public async Task<IActionResult> IncomeCharts(string startTime, string endTime, int type = 0) {
            Result result = new Result {
                code = 1001,
                message = ""
            };

            using (var context = new SqlServerDB()) {
                var admin = await context.Users.FirstOrDefaultAsync(m => m.UserType == UserTypes.超级管理员);
                DateTime startDate = DateTime.Now,
                          endDate = DateTime.Now;

                if ((startTime + "").Length > 0 && (endTime + "").Length > 0) {
                    DateTime.TryParse($"{startTime} 00:00:00", out startDate);
                    DateTime.TryParse($"{endTime} 23:59:59", out endDate);
                } else {
                    DateTime.TryParse(DateTime.Now.ToString("yyyy-MM-01 00:00:00"), out startDate);
                    endDate = DateTime.Now;
                }

                var list = context.Incomes.Where(m => m.CreateTime >= startDate && m.CreateTime <= endDate && m.UserId == admin.Id);

                var orders = context.Orders.Where(m => m.Status == OrderStatus.已发货 && m.CreateTime >= startDate && m.CreateTime <= endDate);

                var orderCount = await orders.CountAsync();
                var saleCount = await orders.SumAsync(m => m.Count);

                var total = list.Where(m => m.SystemType == SystemType.收入).Sum(s => s.IncomePrice).ToString("C");
                var payTotal = list.Where(m => m.SystemType == SystemType.支出).Sum(s => s.IncomePrice).ToString("C");

                if (list.Count() > 0) {
                    if (type > 0) {
                        list = list.Where(m => m.SystemType == (SystemType)type);
                    }

                    var legends = list.GroupBy(g => g.strSystemType).Select(s => s.Key);

                    string[] xAxis = null;

                    List<Dictionary<string, object>> seriess = new List<Dictionary<string, object>>();

                    foreach (var legend in legends) {
                        var groupByTime = await list.Where(w => w.SystemType.ToString() == legend).GroupBy(g => g.CreateTime.ToString("yyyy-MM-dd")).ToListAsync();

                        xAxis = groupByTime.Select(s => s.Key).ToArray();

                        var series = groupByTime.Select(s => s.Sum(m => m.IncomePrice));
                        seriess.Add(new Dictionary<string, object> {
                            { "name", legend},{ "type", "line"},{ "data", series}
                        });
                    }

                    result.code = 0;
                    result.message = "";
                    result.data = new {
                        orderCount,
                        saleCount,
                        total,
                        payTotal,
                        echarts = new {
                            title = new {
                            },
                            tooltip = new {
                                trigger = "axis",
                                axisPointer = new {
                                    type = "cross",
                                    label = new {
                                        backgroundColor = "#6a7985"
                                    }
                                }
                            },
                            legend = new {
                                data = legends.ToArray()
                            },
                            xAxis = new {
                                data = xAxis.ToArray()
                            },
                            yAxis = new {
                                type = "value"
                            },
                            series = seriess
                        }
                    };


                    return Ok(result);
                } else {
                    result.data = new {
                        orderCount,
                        saleCount,
                        total,
                        payTotal
                    };
                    return Ok(result);
                }
            }
        }

        #endregion

        #region Setting
        public async Task<IActionResult> SaveSetting([FromBody]Dictionary<string, string> param) {
            try {
                using (var context = new SqlServerDB()) {
                    var list = await context.Settings.Where(m => m.SystemType == SystemType.收款信息).ToListAsync();

                    string name = param.GetValueOrDefault("name", ""),
                           account = param.GetValueOrDefault("account", ""),
                           bank = param.GetValueOrDefault("bank", ""),
                           alipay = param.GetValueOrDefault("alipay", ""),
                           wechat = param.GetValueOrDefault("wechat", "");

                    if (name.Length > 0) {
                        var nameModel = list.FirstOrDefault(f => f.OtherType == ((int)SystemType.收款人).ToString());

                        if (nameModel != null) {
                            nameModel.Values = name;

                            context.Settings.Update(nameModel);
                        } else {
                            await context.Settings.AddAsync(new SystemSetting {
                                SystemType = SystemType.收款信息,
                                OtherType = ((int)SystemType.收款人).ToString(),
                                Values = name
                            });
                        }
                    }

                    if (account.Length > 0) {
                        var accountModel = list.FirstOrDefault(f => f.OtherType == ((int)SystemType.收款账号).ToString());

                        if (accountModel != null) {
                            accountModel.Values = account;

                            context.Settings.Update(accountModel);
                        } else {
                            await context.Settings.AddAsync(new SystemSetting {
                                SystemType = SystemType.收款信息,
                                OtherType = ((int)SystemType.收款账号).ToString(),
                                Values = account
                            });
                        }
                    }

                    if (bank.Length > 0) {
                        var bankModel = list.FirstOrDefault(f => f.OtherType == ((int)SystemType.收款银行).ToString());

                        if (bankModel != null) {
                            bankModel.Values = bank;

                            context.Settings.Update(bankModel);
                        } else {
                            await context.Settings.AddAsync(new SystemSetting {
                                SystemType = SystemType.收款信息,
                                OtherType = ((int)SystemType.收款银行).ToString(),
                                Values = bank
                            });
                        }
                    }

                    if (alipay.Length > 0) {
                        var alipayModel = list.FirstOrDefault(f => f.OtherType == ((int)CashType.支付宝).ToString());

                        if (alipayModel != null) {
                            alipayModel.Values = alipay;

                            context.Settings.Update(alipayModel);
                        } else {
                            await context.Settings.AddAsync(new SystemSetting {
                                SystemType = SystemType.收款信息,
                                OtherType = ((int)CashType.支付宝).ToString(),
                                Values = alipay
                            });
                        }
                    }

                    if (wechat.Length > 0) {
                        var wechatModel = list.FirstOrDefault(f => f.OtherType == ((int)CashType.微信).ToString());

                        if (wechatModel != null) {
                            wechatModel.Values = wechat;

                            context.Settings.Update(wechatModel);
                        } else {
                            await context.Settings.AddAsync(new SystemSetting {
                                SystemType = SystemType.收款信息,
                                OtherType = ((int)CashType.微信).ToString(),
                                Values = wechat
                            });
                        }
                    }
                    var i = await context.SaveChangesAsync();

                    if (i > 0) {
                        return Ok(new Result {
                            code = 0,
                            success = true,
                            message = "保存成功"
                        });
                    } else {
                        return Ok(new Result {
                            code = 2001,
                            success = true,
                            message = "保存失败"
                        });
                    }
                }
            } catch (Exception ex) {
                return Ok(new Result {
                    code = 1001,
                    success = false,
                    message = ex.InnerException != null ? ex.InnerException.Message : ex.Message
                });
            }
        }

        #endregion

        #region Role
        public IActionResult GetRoleListColumns() {
            List<Columns> list = (typeof(RoleExt).GetColumns()).OrderBy(m => m.order).ToList();

            return Ok(list);
        }

        public async Task<IActionResult> SaveRole(RoleInfo role) {
            try {
                using (var context = new SqlServerDB()) {
                    role.ModuleIds = (role.ModuleIds + "").Length == 0 ? "" : role.ModuleIds;
                    if (role.Id > 0) {
                        context.Roles.Update(role);
                    } else {
                        await context.Roles.AddAsync(role);
                    }

                    var i = await context.SaveChangesAsync();

                    if (i > 0) {
                        return Ok(new Result {
                            code = 0,
                            success = true,
                            message = "保存成功"
                        });
                    } else {
                        return Ok(new Result {
                            code = 2001,
                            success = true,
                            message = "保存失败"
                        });
                    }
                }
            } catch (Exception ex) {
                return Ok(new Result {
                    code = 1001,
                    success = false,
                    message = ex.InnerException != null ? ex.InnerException.Message : ex.Message
                });
            }
        }

        public IActionResult RoleList(int page, int limit) {
            using (var context = new SqlServerDB()) {
                page--;
                CacheHelper cache = new CacheHelper();
                var menus = cache.GetMenuList();

                var list = context.Roles.ToList();

                List<RoleExt> extList = new List<RoleExt>();

                list.ForEach(m => {
                    string[] moduleids = m.ModuleIds.Split(',');

                    List<long> ids = new List<long>();

                    foreach (var id in moduleids) {
                        if (long.TryParse(id, out long i)) {
                            ids.Add(i);
                        }
                    }

                    var r = string.Join(",", menus.Where(w => ids.Contains(w.id)).Select(s => s.name));

                    extList.Add(new RoleExt {
                        Id = m.Id,
                        Text = m.Text,
                        ModuleIds = m.ModuleIds,
                        strModuleIds = r
                    });
                });

                int count = extList.Count();

                return Ok(new {
                    code = 0,
                    msg = "",
                    count,
                    data = extList.Skip(page * limit).Take(limit).ToJsonString()
                });
            }
        }

        public async Task<IActionResult> DelRole(string ids) {
            Result result = new Result();

            using (var context = new SqlServerDB()) {
                if (ids.Length > 0) {
                    List<long> idList = new List<long>();
                    string[] idArray = ids.Split(',');
                    long id = 0;

                    foreach (var i in idArray) {
                        if (long.TryParse(i, out id)) {
                            if (id > 1) {
                                idList.Add(id);
                            }
                        }
                    }

                    if (idList.Count > 0) {
                        var list = context.Roles.Where(m => idList.Contains(m.Id)).ToList();

                        if (list.Count > 0) {
                            List<RoleInfo> removeList = new List<RoleInfo>();
                            foreach (var model in list) {
                                var count = context.UserToRole.Count(m => m.RoleId == model.Id);

                                if (count == 0) {
                                    removeList.Add(model);
                                }
                            }

                            context.Roles.RemoveRange(removeList);

                            int flag = await context.SaveChangesAsync();

                            if (flag > 0) {
                                result.code = 0;
                                result.success = true;
                                result.message = $"删除成功,其中未删除被使用的角色有{(list.Count - removeList.Count)}行";
                            } else {
                                result.code = 1002;
                                result.success = true;
                                result.message = "删除失败，请稍候重试";
                            }

                            return Ok(result);
                        }
                    }
                }
            }


            result.code = 1001;
            result.success = true;
            result.message = "未选择要删除的数据或选择了超级管理员";

            return Ok(result);
        }
        #endregion
    }
}